package com.cmj.job;

import com.cmj.dao.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 定时将浏览量从redis更新入数据库
 */
@Component
public class UpdateViewCountJob {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleMapper articleMapper;

    @Scheduled(cron = "* 0/10 * * * ?")
    public void updateViewCountJob(){
        //获取所有的key值
        Set keys = redisTemplate.opsForHash().keys("article:viewCount");
        for (Object key : keys) {
            articleMapper.updateView(Long.parseLong(key.toString()),
                    (Integer)redisTemplate.opsForHash().get("article:viewCount",key));
        }
        System.out.println("同步过了");
    }
}
